<?php

namespace app\index\controller;

use app\common\model\Order;
use app\common\model\Support;
use app\common\model\User;
use JiGuang\JSMS;
use think\Config;
use think\Controller;
use \think\Request;
use \think\Db;
use think\Session;

class Index extends Controller
{
    /**
     * 登录页面
     * @param Request $request
     * @return \think\response\View
     */
    public function index(Request $request)
    {
        if (!Session::get('username')) {
            if ($request->param('error')) {
                return view('login', ['error' => $request->param('error')]);
            }
            return view('login');
        }
        $user = User::get(['username' => Session::get('username')]);

        //已支持的btc
        // $btcd_num = db('support')->where(['status' => 1])->sum('number');
        $btcd_num = Db::name('support')->where(['status' => 1])->sum('number');
        $totalBtc = $btcd_num / 5;
        return view('index', ['user' => $user, 'totalBtc' => $totalBtc]);
    }

    /**
     * 登录提交
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function upLogin(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['mobile', 'require', '名称必须'],
            ['password', 'require|length:6,16', '密码必须填写|密码长度为6-16个字符'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            // return redirect('/index/index/index', ['error' => $result]);
            $this->error($result);
        }
        $user = User::get(['username' => $request->param('mobile'), 'password' => md5($request->param('password'))]);
        if(!$user){
            $this->error('用户名或密码错误！');
            // return redirect('/index/index/index', ['error' => '用户名或密码错误']);
        }else{
           Session::set('username', $user->username);
           // return redirect('/index/index/index');  
           $this->success('登录成功！','index/index/index');
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::set('username', null);

        return redirect('/index/index/index');
    }

    /**
     * 注册页面
     * @param Request $request
     * @return \think\response\View
     */
    public function register(Request $request)
    {
        if ($request->param('error')) {
            return view('register', ['error' => $request->param('error')]);
        }

        return view('register');
    }

    /**
     * 忘记密码页面
     * @param Request $request
     * @return \think\response\View
     */
    public function forget(Request $request)
    {
        if ($request->param('error')) {
            return view('forget', ['error' => $request->param('error')]);
        }
        return view('forget');
    }

    /**
     * 注册提交
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function upRegister(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['mobile', 'require|unique:user,username', '用户名必须|用户名已存在'],
            ['code', 'require', '验证码必须'],
            ['password', 'require|length:6,16', '密码必须|6-16个字符'],
            ['rePassword', 'require|length:6,16|confirm:password', '密码必须|6-16个字符|两次密码不一致'],
            ['id_card', 'require', '身份证号码必须'],
            ['name', 'require|chs', '真实姓名必须|真实姓名必须为汉字'],
        ]);
        $reg = '/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/';
        if(!preg_match($reg,input('id_card'))){
            $this->error('身份证格式错误！');
        }
        if(true !== $result){
            // 验证失败 输出错误信息
            // return redirect('/index/index/register', ['error' => $result]);
            $this->error($result);
        }
        // dump(input('post.'));die;

        //随机插入地址钱包
        $wallet = randWallet();
        if (!$wallet) {
            // return redirect('/index/index/register', ['error' => '后台钱包地址错误']);
            $this->error('后台钱包地址错误');
        }

        //验证验证码
        if (!checkPhoneCode($request->param('msg_id'), $request->param('code'))) {
            // return redirect('/index/index/register', ['error' => '验证码错误']);
            $this->error('验证码错误');
        }

        //插入数据库
        $res = Db::name('user')->insert([
            'username' => $request->param('mobile'),
            'password' => md5($request->param('password')),
            'id_card'  => $request->param('id_card'),
            'btc_id'   => $wallet,
            'name'     => $request->param('name'),
        ]);
        if(!$res){
            $this->error('网络异常');
        }else{
           $this->success('注册成功', '/index/index/index'); 
        }

    }

    /**
     * 找回密码提交
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function findPassword(Request $request)
    {
        $result = $this->validate($request->param(), [
            ['mobile', 'require', '名称必须'],
            ['code', 'require', '验证码必须'],
            ['password', 'require|length:6,16', '密码必须|6-16个字符'],
            ['re_password', 'require|length:6,16|confirm:password', '确认密码必须|6-16个字符|两次密码不一致'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            // return redirect('/index/index/forget', ['error' => $result]);
            $this->error($result);
        }
        // //验证验证码
        if (!checkPhoneCode($request->param('msg_id'), $request->param('code'))) {
            // return redirect('/index/index/forget', ['error' => '验证码错误']);
            $this->error('验证码错误');
        }

        //修改数据库
        $user = Db::name('user')->where(['username' => $request->param('mobile')])->find();
        if (!$user) {
            // return redirect('/index/index/forget', ['error' => '该用户未注册']);
            $this->error('该用户未注册');
        }
        if ($user['password'] == md5($request->param('password'))) {
            $this->success('设置新密码成功', url('/index/index/index'));
        }
        $res = Db::name('user')->where('username', $request->param('mobile'))->update(['password' => md5($request->param('password'))]);
        if (!$res) {
            $this->error('网络异常');
        }else{
            $this->success('设置新密码成功', '/index/index/index');
        }
    }

    /**
     * 发送短信
     * @param Request $request
     * @return \think\Response
     */
    function sendPhoneCode(Request $request)
    {
        $res = $this->validate($request->param(), [
            'mobile' => 'require|regex:/^1[3578]\d{9}$/',
        ]);
        if ($res !== true) {
            return false;
        }
        $app_key       = Config::get('JiGuang_app_key');
        $master_secret = Config::get('JiGuang_master_secret');
        $client        = new JSMS($app_key, $master_secret, ['ssl_verify' => false]);
        $response      = $client->sendCode($request->post('mobile'), 1);
        if ($response['http_code'] !== 200){
            return json(['msssage' => '参数错误'], $code = 500);
        }
        session(input('mobile'),json_decode($response['body'])->msg_id);
        return json(['msg_id' => json_decode($response['body'])->msg_id], 200);
    }

    /**
     * 支持页面
     * @param Request $request
     * @return \think\response\View
     */
    public function support(Request $request)
    {
        if (!Session::get('username')) {
            return redirect('/index/index/index');
        }
        $user = User::get(['username' => Session::get('username')]);
        if ($request->param('error')) {
            return view('support', ['mobile' => $user->username, 'btc_num' => $user->btc_num, 'error' => $request->param('error')]);
        }
        return view('support', ['mobile' => $user->username, 'btc_num' => $user->btc_num]);
    }

    /**
     * 支持提交
     * @param Request $request
     * @return \think\response\View
     */
    public function upSupport(Request $request)
    {
        if (!Session::get('username')) {
            return redirect('/index/index/index');
        }
        $result = $this->validate($request->param(), [
            ['number', 'require', '数量必须'],
            ['code', 'require', '验证码'],
        ]);
        if(true !== $result) {
            // 验证失败 输出错误信息
            // return redirect('/index/index/support', ['error' => $result]);
            $this->error($result);
        }
        //验证还差多少btc
        $totalBtc = Db::name('support')->sum('number');
        if($totalBtc>=700){
            $this->error('该众筹已结束！');
        }else{
            $poor_Btc = 700-$totalBtc;
            if(input('number')>$poor_Btc){
                $this->error('该众筹还差'.$poor_Btc.'BTC！,请重新输入支持数量！');
            }
        }
        if (!checkPhoneCode($request->param('msg_id'), $request->param('code'))) {
            // return redirect('/index/index/support', ['error' => '验证码错误']);
            $this->error('验证码错误');
        }
        $user = User::get(['username' => Session::get('username')]);
        if ($user->btc_num < $request->param('number')) {
            // return redirect('/index/index/support', ['error' => '比特比不足']);
            $this->error('比特比不足');
        }
        try {
            Db::transaction(function() use ($user, $request) {
                Db::name('support')->insert([
                    'user_id' => $user->id,
                    'number'  => $request->param('number'),
                    'time'    => time(),
                ]);
                Db::name('user')->where(['id' => $user->id])->setInc('btcd_num', $request->param('number'));
                Db::name('user')->where(['id' => $user->id])->setDec('btc_num', $request->param('number'));
            });
        } catch (\Exception $e) {
            $this->error('网络异常');
        }
        $this->success('订单创建成功！', 'index/index/index');
    }

    /**
     * 支持订单
     */
    public function supportOrder()
    {
        if (!Session::get('username')) {
            return redirect('/index/index/index');
        }
        $user     = User::get(['username' => Session::get('username')]);
        $supports = Support::all(['user_id' => $user->id]);

        return view('support_order', ['supports' => $supports]);
    }

    /**
     * 订单页面
     * @return \think\response\View
     */
    public function order()
    {
        if (!Session::get('username')) {
            return redirect('/index/index/index');
        }
        $user   = User::get(['username' => Session::get('username')]);
        $orders = Order::all(['user_id' => $user->id]);

        return view('ico_order', ['orders' => $orders]);
    }

    /**
     * 充值页面
     * @param Request $request
     * @return \think\response\View
     */
    public function recharge(Request $request)
    {
        if (!Session::get('username')) {
            return redirect('/index/index/index');
        }
        $user = User::get(['username' => Session::get('username')]);
        if ($request->param('error')) {
            return view('recharge', ['toAddress' => $user->btc_id, 'error' => $request->param('error')]);
        }
        return view('recharge', ['toAddress' => $user->btc_id]);
    }

    /**
     * 冲值提交
     * @param Request $request
     * @return \think\response\Redirect
     */
    public function upRecharge(Request $request)
    {
        if (!Session::get('username')) {
            return redirect('/index/index/index');
        }
        $result = $this->validate($request->param(), [
            ['btc_address', 'require', '地址不能为空'],
            ['re_btc_address', 'require|confirm:btc_address', '确认地址不能为空|两次地址不一样'],
            ['number', 'require|number', '数量不能为空|数量错误'],
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            // return redirect('/index/index/recharge', ['error' => $result]);
            $this->error($result);
        }
        $user   = User::get(['username' => Session::get('username')]);
        $result = Order::create([
            'user_id'  => $user->id,
            'btc_user' => $request->param('btc_address'),
            'btc_web'  => $user->btc_id,
            'btc_num'  => $request->param('number'),
            'time'     => time(),
        ]);
        if (!$result) {
            $this->error('网络异常！');
        }else{
            $this->success('订单创建成功！', '/index/index/index');
        }
     
    }

    //检查是否已注册
    public function check_is_register(){
        $username = input('username');
        $check = Db::name('user')->where('username',$username)->find();
        if($check){
            return json(['code'=>1]);
        }else{
            return json(['code'=>0]);
        }

    }

    public function information()
    {
        return view('information');
    }

    //检测图形验证码
    public function check_img_code()
    {   
        $img_code = input('img_code');
        if(!captcha_check($img_code)){
            $this->error('图形验证码错误！');
        }else{
            $this->success('图形验证码正确！');
        }
    }   
}
